package fragments;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yztc.thinkpad.mandemo.R;
import com.yztc.thinkpad.mandemo.cooladapter.Cool_RecyclerAdapter;
import com.yztc.thinkpad.mandemo.coolbean.CoolDataBean;
import com.yztc.thinkpad.mandemo.coolconstant.Constant;

import java.io.IOException;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import utils.Okhttputils;

/**
 * Created by Administrator on 2016/10/5.
 */
public class CoolPagerFragment extends Fragment {

    @Bind(R.id.cool_SwipeRefreshLayout)
    SwipeRefreshLayout coolSwipeRefreshLayout;
    RecyclerView coolRv;
    @Bind(R.id.cool_fab)
    FloatingActionButton coolFab;
    ProgressDialog pd;
    private String run;
    private int lastVisibleItem;
    private int lastItemCount;
    private View view;
    private LinearLayoutManager manager;
    private int mScrollThreshold;
    public void setScrollThreshold(int scrollThreshold) {
        mScrollThreshold = scrollThreshold;
    }
    //页码
    private int page = 1;

    //viewpager的改变
    private int i;
    private List<CoolDataBean> coolDataBeen;
    private List<CoolDataBean> mCoolDataBean;
    //    private CoolAdapter adapter;
    private Cool_RecyclerAdapter adapter;
    private Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            pd.dismiss();
            if (page == 1) {
                mCoolDataBean = (List<CoolDataBean>) msg.obj;
                adapter = new Cool_RecyclerAdapter(getActivity(), mCoolDataBean);
                coolRv.setAdapter(adapter);
                lastVisibleItem = manager.findLastVisibleItemPosition();
            } else {
                /*coolDataBeen.addAll((List<CoolDataBean>) msg.obj);
                adapter.notifyDataSetChanged();*/
                adapter.rush((List<CoolDataBean>) msg.obj, false);
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = LayoutInflater.from(getActivity()).inflate(R.layout.cool_listview, null);
//        Log.e("tag", "========="+i );
        coolRv = (RecyclerView) view.findViewById(R.id.cool_rv);
        ButterKnife.bind(this, view);
        Cool_RecyclerAdapter.load_more_status=0;
        initview();
        initdata(true);
        refresh();
        initcallback();
        initsilde();
        return view;
    }
    //滑动隐藏和显示FAB
    private void initsilde() {
        coolRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                boolean isSignificantDelta = Math.abs(dy) > mScrollThreshold;
                if (isSignificantDelta) {
                    if (dy > 0) {
                        onScrollUp();
                    } else {
                        onScrollDown();
                    }
                }
            }

            private void onScrollDown() {

                coolFab.setVisibility(View.VISIBLE);
            }

            private void onScrollUp() {
                coolFab.setVisibility(View.GONE);
            }
        });
    }

    //回调fab获取焦点完成点击回到RecyclerView的顶部
    private void initcallback() {
        coolFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manager.scrollToPositionWithOffset(0,0);
            }
        });
    }

    //刷新数据
    private void refresh() {
        //加载更多
        coolRv.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(final RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                lastItemCount = manager.getItemCount();
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                                if(coolDataBeen.size()!=0) {
                                    page++;
                                    Cool_RecyclerAdapter.load_more_status = 0;
                                    initdata(false);
                                 }else{
                                    Cool_RecyclerAdapter.load_more_status = 1;
                                    initdata(false);
                                }
                        }
                    });
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = manager.findLastVisibleItemPosition();
            }
        });
        //设置刷新时动画的颜色  可以设置4个
        coolSwipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light
        );
        //下拉刷新
        coolSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (page == 1) {
                            initdata(false);
                        }
                        coolSwipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        });
    }

    //初始化数据
    private void initview() {
       pd=new ProgressDialog(getActivity());
        i = getArguments().getInt("kind");
        /**
         * RecyclerView.LayoutManager 抽象类
         * LinearLayoutManager 线性布局管理器  纵向横向
         */
        manager = new LinearLayoutManager(getActivity());
        coolRv.setLayoutManager(manager);
        /**
         * 调用addItemDecoration()方法添加item之间的间距
         * ItemDecoration抽象类 需要定义单独的子类定义item之间的间距
         *
         *  onDraw()或者onDrawOver()  getItemOffsets()
         *
         *  自定义分割线实现类通过读取系统主题中的android.R.attr.listDivider
         *  作为item的分割线
         */
//        coolRv.addItemDecoration(new DividerItemDecoration(getActivity(),
//                DividerItemDecoration.VERTICAL_LIST));
        /**
         * 为recyclerView中item添加动画效果   ItemAnimator抽象类
         * DefaultItemAnimator系统提供的默认效果
         */
//        Animation animation1= AnimationUtils.loadAnimation(getActivity(),R.anim.into);
        coolRv.setItemAnimator(new DefaultItemAnimator());
    }

    //获取网络数据 传递到handle
    private void initdata(boolean b) {
        if (b){
            pd.setMessage("正在加载数据。。。");
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pd.show();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    run = Okhttputils.getInstance().run(Constant.COOLLEFT + i + Constant.PAGE + page + Constant.COOLRIGHT);
//                    Log.e("tag",")))))))))"+run);
                    String data = JSONObject.parseObject(run).getString("data");
                    coolDataBeen = JSONArray.parseArray(data, CoolDataBean.class);
//                    Log.e("tag",")))))))))"+coolDataBeen.size());
                    Message msg = new Message();
                    msg.obj = coolDataBeen;
                    mHandle.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

}
